package l1j.opqlo.Timer.NpcControler;

import java.util.Collection;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.WorldNpc;
import l1j.server.Thread.GeneralThreadPool;
import l1j.server.server.model.Instance.L1NpcInstance;

/**
 * NPC死亡時間軸
 *
 * @author dexc
 *
 */
public class NpcDeadTimer extends TimerTask {

	private static final Logger _log = Logger.getLogger(NpcDeadTimer.class.getName());


	private ScheduledFuture<?> _timer;

	@Override
	public void run() {
		try {
//			final PerformanceTimer timer = new PerformanceTimer();
			final Collection<L1NpcInstance> allMob = WorldNpc.get().all();
//			final Collection<L1NpcInstance> allMob = WorldNpc.get().all().parallelStream()
//					.filter(L1NpcInstance -> L1NpcInstance !=null)
//					.filter(L1NpcInstance -> L1NpcInstance.isDead())
//					.collect(Collectors.toList());
//			// 不包含元素
//			if (allMob.isEmpty()) {
//				return;
//			}
//			
//			final Collection<L1NpcInstance>  deadMob = allMob.parallelStream()
//			.filter(L1NpcInstance -> L1NpcInstance.getMaxHp()>0)
//			.filter(L1NpcInstance -> L1NpcInstance.get_deadTimerTemp() != -1)
//			.collect(Collectors.toList());
//			
//			deadMob.forEach(L1NpcInstance -> L1NpcInstance.set_deadTimerTemp(L1NpcInstance.get_deadTimerTemp()-5));
//			
//			final Collection<L1NpcInstance> clearMob = deadMob.parallelStream()
//					.filter(L1NpcInstance -> L1NpcInstance.get_deadTimerTemp() <=0)
//					.collect(Collectors.toList());
//			
//			clearMob.forEach(L1NpcInstance -> L1NpcInstance.deleteMe());
			
			// 不包含元素
			if (allMob.isEmpty()) {
				return;
			}
			final Iterator<L1NpcInstance> iterator =allMob.iterator();
			while(iterator.hasNext()){
				final L1NpcInstance npc = iterator.next();
				if (npc == null) {
					continue;
				}
				if (npc.getMaxHp() <= 0) {
					continue;
				}
				// 未死亡(復活可能)
				if (!npc.isDead()) {
					continue;
				}
				if (npc.get_deadTimerTemp() == -1) {
					continue;
				}
				final int time = npc.get_deadTimerTemp();
				npc.set_deadTimerTemp(time - 3);

				if (npc.get_deadTimerTemp() <= 0) {
					npc.deleteMe();
				}
				Thread.sleep(1);
			}
		} catch (final Exception e) {
			_log.log(Level.WARNING, "NPC死亡時間軸異常重啟", e);
			GeneralThreadPool.getInstance().cancel(this._timer, false);
			final NpcDeadTimer npcDeadTimer = new NpcDeadTimer();
			npcDeadTimer.start();
		}
	}

	public void start() {
		final int timeMillis = 3000;// 3秒
		this._timer = GeneralThreadPool.getInstance().scheduleAtFixedRate(this,timeMillis, timeMillis);
	}
}
